#include <boost/tokenizer.hpp>
#include "FontManager.h"
#ifdef DEBUG_NEW
#include "debug/debug_new.h"
#endif

FontFace::FontFace(int height) {
    _textures = new GLuint[128];
    glGenTextures(128, _textures);
    _lists = glGenLists(128);
    _height = (float) height;
    _widths = new float[128];

}

FontFace::~FontFace() {
    glDeleteTextures(128, _textures);
    glDeleteLists(_lists, 128);
    delete [] _textures;
    delete [] _widths;
}

float FontFace::h() {
    return _height;
}

GLuint FontFace::texture(int ch) {
    return _textures[ch];
}

GLuint FontFace::list(int ch) {
    return _lists + ch;
}

void FontFace::set_width(int ch, float w) {
    _widths[ch] = w;
}

float FontFace::get_width(int ch) {
    return _widths[ch];
}

float FontFace::get_str_width(const string& text) {
    float w = 0.0f;
    for (size_t i = 0; i < text.length(); ++i) {
        w += _widths[(int)text[i]];
    }
    return w;
}

void FontFace::str_to_width(const string& orig, string& out, float width) {
    out = "";
    char_separator<char> sep("\n");
    tokenizer<char_separator<char> > tokens(orig, sep);
    tokenizer<char_separator<char> >::iterator it;
    for (it = tokens.begin(); it != tokens.end(); it++) {
        string line = *it;
        if (get_str_width(line) < width) {
            out.append(line);
            out.append("\n");
        } else {
            char_separator<char> sep_l(" ");
            tokenizer<char_separator<char> > tokens_l(line, sep_l);
            float c_l = 0.0f;
            string line_l = "";
            for (tokenizer<char_separator<char> >::iterator it_l = tokens_l.begin();
                    it_l != tokens_l.end(); ++it_l) {
                float ll = get_str_width(*it_l);
                if (c_l + ll > width) {
                    line_l.append("\n");
                    line_l.append(*it_l);
                    line_l.append(" ");
                    c_l = ll;
                } else {
                    //32 is the character code for space
                    c_l += ll + get_width(32);
                    line_l.append(*it_l);
                    line_l.append(" ");
                }
            }
            out.append(line_l);
            out.append("\n");
        }
    }
    //return out;

    //return text;
}